package cn.wolfcode.util;

import cn.wolfcode.domain.LogInfo;
import cn.wolfcode.mapper.LogInfoMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;


@Component //把当前类注入到spring容器中
@Aspect    //把当前类标识为一个切面供容器读取
public class AopConfig {

    /**
     * 指定切入点
     * 对贴有自定义注解@RequiredPermission的方法，进行切面
     */
    @Pointcut("@annotation(cn.wolfcode.util.RequiredPermission)")
    private void useMethod() {}

    @Autowired
    private LogInfoMapper logInfoMapper;

    @Autowired
    private HttpServletRequest httpServletRequest;

    private  static long startTime;

    /**
     * 对切入点进行增强
     * 前置执行
     */
    @Before(value = "useMethod()")
    public Object recordLog(JoinPoint joinPoint) throws Throwable {
        startTime=System.currentTimeMillis();
        //创建日志管理对象
        LogInfo logInfo = new LogInfo();
        //设置用户名
        logInfo.setUsername(UserContext.getCurrentUser().getName());

        //执行处理方法（执行控制器中的方法）
        Object result = joinPoint.getTarget();
        Object[] args = joinPoint.getArgs();
        if (args.length>0){
            int index = args[0].toString().indexOf(", org.springframework.");
            if (index!=-1){
                logInfo.setArgs(args[0].toString().substring(0,index));
            }else {
                logInfo.setArgs(args[0].toString());
            }
        }
        //获取请求参数


        //获取请求方法
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        System.out.println(method.getName());

        RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
        //获取方法请求方法
       logInfo.setRequest(annotation.expression());
        //获取用户操作
        logInfo.setOperation(annotation.name());

        //获取id地址
        logInfo.setIp(UserContext.getRealIp(httpServletRequest));
        //设置一个唯一id
        String uuid = UUID.randomUUID().toString();
        logInfo.setUuid(uuid);
        //设置唯一id
        UserContext.setUUID(uuid);

        //设置操作时间
        logInfo.setCreatetime(new Date());
        //设置默认操作
        logInfo.setResult(true);
        //默认错误信息
        logInfo.setError("无");
        //直接插入对象
        logInfoMapper.insert(logInfo);

        //result是方法的返回值，直接return回去就会返回给springmvc处理
        return result;
    }


    //统计毫秒数
    @After(value = "useMethod()")
    public Object After(JoinPoint joinPoint) {
        Object proceed = joinPoint.getTarget();

        long endTime=System.currentTimeMillis();
        //获取执行时间
        long excTime=endTime-startTime;
        //通过登录的用户名查询出该用户
        Long id = logInfoMapper.getLogInfoByUUID(UserContext.getUUID());
        //再通过id修改对应的耗时
        logInfoMapper.updateRuntimeById(id,excTime);
        return proceed;
    }

}